package com.sinog.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinog.basic.mapper.DepartmentMapper;
import com.sinog.basic.mapper.UserInterFaceMapper;
import com.sinog.basic.mapper.UserMapper;
import com.sinog.basic.mapper.common.CommonBasicMapper;
import com.sinog.basic.service.UserService;
import com.sinog.core.domain.User;
import com.sinog.core.domain.UserInterFaceEntity;
import com.sinog.core.domain.UserPosition;
import com.sinog.core.model.UserDTO;
import com.sinog.core.model.UserPositionVo;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @desc 系统管理 - 用户管理 - 用户管理 - UserServiceImpl
 * @author -
 * @date -
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private CommonBasicMapper commonBasicMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private UserInterFaceMapper userInterFaceMapper;
    @Value("${gkzx.azbj.security.user-default-password-reset}")
    private String password;

    /**
     * 系统管理 - 用户管理 - 用户管理 - 保存用户信息（更新/新增）
     * @param data data
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(String data) {
        User bean = JsonUtil.toBean(data,User.class);
        //1、判断是新增还是修改
        Long aLong = userMapper.checkAccount(bean.getAccount());
        if(0 >= aLong) {
            new Thread(() -> {
                log.debug("异步处理用户机构缓存");
                //2、新增
                //判断该用户的departId是否在用户机构缓存表存在
                Integer i = commonBasicMapper.existDepartId(bean.getDepartid());
                //不存在，添加一条
                if(null == i) {
                    int k = commonBasicMapper.insertCache(bean.getDepartid());
                    if(0 < k) {
                        //把全部上级追加本机构ID
                        List<String> pidss = departmentMapper.selectCache(bean.getOrgid());
                        List<Map<String,String>> caches = commonBasicMapper.selectCacheByIds(pidss);
                        for(Map<String,String> map : caches) {
                            String childid = map.get("childid");
                            childid = childid + bean.getOrgid() + ",";
                            commonBasicMapper.updateCacheById(map.get("id"),childid);
                        }
                    }
                }
            },"Thread-user-1").start();
        }
        boolean success = bean.insertOrUpdate();
        //这个只是在添加社矫中心账号或者修改社矫账号才会执行
        if(Constants.RoleId.ROLE_ID_SJZX.equals(bean.getRoleid()) && !StringUtils.isEmpty(bean.getAccount())) {
            //需要去tbsys_user_interface再插入一个账号，这个是对外同步数据的
            UserInterFaceEntity userInterFaceEntity = new UserInterFaceEntity();
            BeanUtils.copyProperties(bean,userInterFaceEntity);
            //固定的一个uid
            userInterFaceEntity.setUid(Constants.USER_INTERFACE_UID);
            //前提是账户不为空
            Integer count = userInterFaceMapper.selectCount(new QueryWrapper<UserInterFaceEntity>().eq("account",userInterFaceEntity.getAccount()));
            if(count == 1) {
                userInterFaceMapper.updateById(userInterFaceEntity);
            } else {
                userInterFaceMapper.insert(userInterFaceEntity);
            }
        }
        if(success) {
            return Result.success("操作成功!");
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 分页查询用户信息
     * @param usernameKey usernameKey
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param pid 选择的部门父级id
     * @param id 选择的部门id
     * @param orgid orgid
     * @param loginUserDepartid 当前登录单位id
     * @return String
     */
    @Override
    public String selectUserList(String usernameKey,Integer pageIndex,Integer pageSize,String pid,String id,String orgid,String loginUserDepartid) {
        usernameKey = StrUtil.converseToNull(usernameKey);
        String departid;
        String mark = "-1";
        if(mark.equals(pid)) {
            departid = null;
        } else {
            departid = id;
        }
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(userMapper.selectUserList(page,usernameKey,orgid,departid,loginUserDepartid));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 删除用户
     * @param id id
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOne(String id) {
        int i = userMapper.deleteUserByAccount(id);
        //如果一条用户删除了，需要去同步删除一下用户接口表中的一个用户账号
        userInterFaceMapper.deleteById(id);
        if(0 < i) {
            return Result.success("删除成功!");
        }
        return Result.failure(ReturnCode.DELETE_FAILED);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据id查询用户
     * @param account account
     * @param avatarFlag 0:不需要查询头像avatar。1：需要查询avatar
     * @return Result
     */
    @Override
    public Result selectOne(String account,String avatarFlag) {
        UserDTO result = baseMapper.selectUserByAccount(account,avatarFlag);
        if(null != result) {
            return Result.success(JsonUtil.toText(result));
        }
        return Result.failure(ReturnCode.SELECT_FAILED);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 修改用户电话号码邮箱
     * @param account account
     * @param phone phone
     * @param email email
     * @param username username
     * @param telphone telphone
     * @return Result
     */
    @Override
    public Result updateUserInfoOne(String account,String phone,String email,String username,String telphone) {
        if(Constants.NumberStr.NUM_STR_FU_ONE.equals(telphone)) {
            telphone = "";
        }
        int result = userMapper.updateUserInfo(account,phone,email,username,telphone);
        if(Constants.Number.NUM_ONE == result) {
            return Result.success("修改成功！");
        }
        return Result.failure(ReturnCode.FAILURE,"修改失败！");
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 更新头像
     * @param account account
     * @param basefile basefile
     * @return Result
     */
    @Override
    public Result updateUserHead(String account,String basefile) {
        int result = userMapper.updateHeadPic(account,basefile);
        if(1 == result) {
            return Result.success("更新成功！ 请重新登录");
        }
        return Result.failure(ReturnCode.FAILURE,"更新失败！");
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据账号查询
     * @param account account
     * @return UserInterFaceEntity
     */
    @Override
    public UserInterFaceEntity getInfoByAccount(String account) {
        return commonBasicMapper.getInfoByAccount(account);
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据账号重置密码
     * @param account account
     * @return Result
     */
    @Override
    public Result resetPwd(String account) {
        int result = commonBasicMapper.resetPwd(account,password);
        if(1 == result) {
            return Result.success("重置成功");
        }
        return Result.failure(ReturnCode.FAILURE,"重置失败");
    }

    /**
     * 系统管理 - 用户管理 - 用户管理 - 根据部门ID查询部门下全部子部门ID
     * @param departid departid
     * @return List<String>
     */
    @Override
    public List<String> selectAllDepartIdByDepartid(String departid) {
        return userMapper.selectAllDepartIdByDepartid(departid);
    }

    /**
     * 系统管理 - 用户管理 - 新增 - 校验手机号是否重复
     * @param phoneNum 手机号码
     * @param account 当前账户
     * @return Result
     */
    @Override
    public Result checkPhone(String phoneNum,String account) {
        List<UserDTO> userDtos = userMapper.checkPhone(phoneNum);
        if (userDtos.isEmpty()) {
            return Result.success("手机号可用");
        } else if (userDtos.size() == 1 && account.equals(userDtos.get(0).getAccount())) {
            return Result.success("手机号可用");
        } else {
            //说明数据库中存在相同的电话
            return Result.failure(ReturnCode.USER_ALREADY_EXIST,"手机号已被注册");
        }
    }

    /**
     * 山西个性化代码 首页 - 用户信息 - 修改
     * @param userPositionStr account
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateUserPositionById(String userPositionStr) {
        UserPositionVo upvo = JsonUtil.toBean(userPositionStr, UserPositionVo.class);
        try {
            User user = new User();
            user.setAccount(upvo.getAccount());
            user.setUsername(upvo.getUsername());
            user.setPhone(upvo.getPhone());
            user.setTelphone(upvo.getTelphone());
            user.setEmail(upvo.getEmail());
            UserPosition userPosition = new UserPosition();
            userPosition.setAccount(upvo.getAccount());
            userPosition.setPostCode(upvo.getPostCode());
            userPosition.setPositionPro(upvo.getPositionPro());
            userPosition.setPositionCity(upvo.getPositionCity());
            userPosition.setPositionCou(upvo.getPositionCou());
            userPosition.setPositionVill(upvo.getPositionVill());
            if (userMapper.selectUserPositionByAccount(upvo.getAccount()) == null) {
                userMapper.insertUserPosition(userPosition);
            }
            userMapper.updateUserByAccount(user);
            userMapper.updateUserPositionByAccount(userPosition);
            return Result.success(ReturnCode.SUCCESS);
        }catch (Exception e){
            return Result.failure(ReturnCode.SAVE_FAILED);
        }
    }

    /**
     * 山西个性化需求 - 根据account查询用户详情 获取主页右上方用户信息
     * @param account
     * @return Result
     */
    @Override
    public Result selectUserPositionInfo(String account) {
        UserPositionVo result = userMapper.selectUserPositionInfo(account);
        if(result != null) {
            result.setPositionProName(getAreaNameByCode(result.getPositionPro()));
            result.setPositionCityName(getAreaNameByCode(result.getPositionCity()));
            result.setPositionCouName(getAreaNameByCode(result.getPositionCou()));
            result.setPositionVillName(getAreaNameByCode(result.getPositionVill()));
            return Result.success(JsonUtil.toText(result));
        }
        return Result.failure(ReturnCode.SELECT_FAILED);
    }

    /**
     * 山西个性化需求 - 获取地区名称
     * @param areaCode areaCode
     * @return String
     */
    public String getAreaNameByCode(String areaCode){
        return userMapper.getAreaNameByCode(areaCode);
    }
}